package com.xrit.service;

import com.xrit.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;


public class UserServie implements UserDetailsService {
    @Autowired
    UserDao userDao;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //调用findByUsername方法
        com.xrit.pojo.User user = userDao.findByUsername(username);
        //创建ArrList
        ArrayList<GrantedAuthority> authorities = new ArrayList<>();
        //创建SimpleGrantedAuthority对象并加入权限
        SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_ADMIN");
        //将权限添加进ArrList
        authorities.add(grantedAuthority);
        //将security需要登陆用户信息添加进User
        UserDetails userDetails = new User(username, user.getPassWord(), authorities);
        //返回User
        return userDetails;
    }

    /**
     * 测试BCryptPasswordEncoder加密
     */
    public static void main(String[] args) {
        //创建BCryptPasswordEncoder
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

        // encode加密
        /*String encode = bCryptPasswordEncoder.encode("123");
        System.out.println(encode);*/

        // 密码匹配
        // 明文
        // 密文
        boolean matches = bCryptPasswordEncoder.matches("123", "$2a$10$qB8n7dak.XoYaT9XxabRTeh.XnHc/QKaKRYF/Dq3w9LEQ4lzmgvPO");
        String encode = bCryptPasswordEncoder.encode("123456");
        System.out.println(encode);
    }
}
